<?php
/**
 * Class Base Controller
 * Controll General Action
 */
class BaseController extends Zend_Controller_Action
{

	protected $page_title="";
	protected $page_des="";
	protected $page_layout='layout';

	# load header file for master page
	protected $page_header='header';
	# include css with language
	# include file css, js to header page
	protected $load_header='';
	protected $type=0;
	protected $auth;

	public function preDispatch()
	{
		$key = Zend_Registry::get ('CurrentRoute');
		//var_dump($key);die;
			
		if ($key == 'by_index'){
			//$key .= '_'.$this->type;
			$key = $this->view->translate('by_type_0');
			$this->_redirect ('/'.$key);
			exit;
		}
		if (strpos ($key, '_1')){
			$this->type = 1;
			$this->getRequest()->setParam('type',1);
		}elseif (strpos ($key, '_0')){
			$this->type = 0;
			$this->getRequest()->setParam('type', 0);
		}
			

		$this->setLayout();
		$this->placeHeader();
		$this->placeSearch();
		$this->placeFooter();
		#$this->repareLanguage();
		$this->load_header .= '<script language="javascript">var type='.$this->type.';</script>'."\n";

		$this->view->H1 = $this->view->translate($key.'_h1');
		$this->page_title = $this->view->translate($key.'_title');
		$this->page_des = $this->view->translate($key.'_desc');



	}

	protected function setLayout(){
		$this->_helper->layout()->setLayout($this->page_layout);
	}

	public function placeHeader()
	{
		$defaultType = $this->type;
			
		$request=$this->getRequest();

		$controller = $request->getControllerName();
		$hidden_login = $request->getPost('hidden_login','');
		$authenticate = new Defined_Authenticate();

		$nexturl = '/user/edit/';
		if($request->isPost() && $hidden_login=='login' ){
			$username = $request->getPost('user');
			$passwd = $request->getPost('pass');

			if($authenticate->login($username, md5($passwd)) !== true){
				$this->view->CALL_SCRIPT = 'alert ("Đăng nhập không thành công, vui lòng thử lại!")'."\n";
				//$this->view->ERROR_MES = 'Ä�Äƒng nháº­p khĂ´ng thĂ nh cĂ´ng, vui lĂ²ng thá»­ láº¡i!';
			}elseif($authenticate->isLogged()===true){
				$this->auth = $authenticate->getIdentity();

				$active=intval($this->auth->active);
				if($active==1){
					/* if(trim($_COOKIE['referrer'])!=''){
					 $nexturl=$_COOKIE['referrer'];
					 setcookie('referrer','',time()+30*24*60*60,'/');
					 } */
					$this->_redirect($nexturl);
					exit();
				} /* else{
				$authenticate->logout();
				$this->view->CALL_SCRIPT = 'alert ("TĂ i khoáº£n chÆ°a kĂ­ch hoáº¡t!")'."\n";
				//$this->view->ERROR_MES = 'TĂ i khoáº£n chÆ°a kĂ­ch hoáº¡t!';
				} */
			}


		}

		if($authenticate->isLogged()===true){
			$this->auth = $authenticate->getIdentity();
			$this->view->NAME = $this->auth->last_name . ' '.$this->auth->first_name;

			$this->view->FORM_LOGIN = $this->view->render('main/logined.phtml');
		}else{
			$this->view->FORM_LOGIN = $this->view->render('main/form_login.phtml');
		}



		// Set cookie for type search

		$request_type=$request->getParam('type', '');
			
		if(trim($request_type)!=''){
			setcookie('type',$request_type,time()+30*24*60*60,'/');
			$_SESSION['type']=$request_type;
		}else{
			if(isset($_COOKIE['type'])){
				$request_type=isset($_SESSION['type'])?$_SESSION['type']:$_COOKIE['type'];

			} else {
				$request_type=isset($_SESSION['type'])?$_SESSION['type']:$defaultType;

			}
		}

		/*If has id param, Get type*/
		//$controller = $this->_request->getControllerName();
		$actname = $this->_request->getActionName();
		$id = $this->_request->getParam('id',0);
		if ($controller=='user'&&$actname=='post'&&$id>0)
		{
			$mMotor = new Motor();
			$bmotor =  $mMotor->getMotorByID ($id, $this->auth->id);
			$this->view->MOTOR_INFO = $bmotor;
			$request_type = $bmotor['type'];
		}
			

		/********/
		$this->type=$request_type;
		$this->view->TYPE=$request_type;
		$header = $this->view->render('main/'.$this->page_header.'.phtml');
		$this->view->placeholder('header')->set($header);
		
		//online counting
		$mOnlinecount = new Defined_UsersOnline();
		$statistics = $mOnlinecount->statistics();		
		$this->view->ONLINECOUNT = $statistics;	
		$right=$this->view->render('main/right.phtml');
		$this->view->placeholder('right')->set($right);
	}

	public function placeSearch()
	{
		//If has id param, Get type
		/*$controller = $this->_request->getControllerName();
		 $actname = $this->_request->getActionName();
		 $id = $this->_request->getParam('id',0);
		 if ($controller=='user'&&$actname=='post'&&$id>0)
		 {
		 $mMotor = new Motor();
		 $bmotor =  $mMotor->getMotorByID ($id, $this->auth->id);
		 $this->view->MOTOR_INFO = $bmotor;
		 $this->type = $bmotor['type'];
		 $this->view->TYPE = $bmotor['type'];
		 }*/

		$arrGet=$this->getRequest()->getParams();
		$mMotor=new Motor();
		$arrManufacture=$mMotor->getManufacture($this->type,'name','ASC');
		$this->view->ARR_FACTORY=$arrManufacture;

		//var_dump($arrGet);
		if(isset($arrGet['manufacture'])&& $arrGet['manufacture']!=''){
			$arrModel = $mMotor->getModelByManuAlias($arrGet['manufacture'],'name','ASC');

			// Edit 13/09/2011
			if ($this->type) $sAlias ='model-oto-khac';
			else $sAlias ='model-xm-khac';
			$arrModel[] = array (
                'id'=>0,
                'type'=>$this->type,
                'alias'=>$sAlias,
                'name'=>'KhĂ¡c'
                );
                // END Edit 13/09/2011

                if($arrGet['manufacture']=="xm-khac" ||$arrGet['manufacture']=="oto-khac" ) {
                	$arrModel=$mMotor->getModel($this->type,'name','ASC');
                }
		} else {
			$arrModel=$mMotor->getModel($this->type,'name','ASC');
		}

		//var_dump($arrModel);
		$this->view->ARR_MODEL=$arrModel;

		$arrCity=$mMotor->getCity('name','ASC');
		$this->view->ARR_CITY=$arrCity;

		$arrPrice=$mMotor->getPrice($this->type);
		$this->view->ARR_PRICE=$arrPrice;

		$arrStyle=$mMotor->getStyle('name','ASC');
		$this->view->ARR_STYLE=$arrStyle;

		// Parse to html
		$sFactory=$sModel=$sCity=$sPrice=$sStyle='';
		foreach($arrManufacture as $data){
			$this->view->SELECTED='';
			$this->view->NAME =$data['name'];
			$this->view->VALUE =$data['alias'];
			if(isset ($arrGet['manufacture']) && $data['alias']==$arrGet['manufacture'])
			$this->view->SELECTED='selected="selected"';
			$sFactory.=$this->view->render('common-item/item_factory.phtml');
		}

		// eidt by Tin 09/09/2011
		//$sManufactureSelected = '';
		//if ( isset ($arrGet['manufacture']) && $arrGet['manufacture'] == 'xm-khac'){
		//    $sManufactureSelected = 'selected="selected"';
		//}
		//$sFactory .= '<option '. $sManufactureSelected .' value="xm-khac"> KhĂ¡c </option>';
		// end eidt by Tin 09/09/2011
		$this->view->HTML_FACTORY=$sFactory;

		$arModel =array ();
		//var_dump($arrModel);
		foreach($arrModel as $data){
			$this->view->SELECTED='';
			$this->view->NAME =$data['name'];
			$this->view->VALUE =$data['alias'];
			if(isset ($arrGet['model']) && $data['alias']==$arrGet['model'])
			$this->view->SELECTED='selected="selected"';
			$sModel.=$this->view->render('common-item/item_model.phtml');
			$arModel[$data['alias']] = $data;
		}

		//$sModel .= '<option value="model-xm-khac"> KhĂ¡c </option>';
		$this->view->ALIAS_MODEL=$arModel;
		$this->view->HTML_MODEL=$sModel;
		//var_dump($sModel);


		foreach($arrCity as $data){
			$this->view->SELECTED='';
			$this->view->NAME =$data['name'];
			$this->view->VALUE =$data['alias'];
			if(isset ($arrGet['city']) && $data['alias']==$arrGet['city'])
			$this->view->SELECTED='selected="selected"';
			$sCity.=$this->view->render('common-item/item_city.phtml');



		}
		$this->view->HTML_CITY=$sCity;

		foreach($arrPrice as $data){
			$this->view->NAME = $data['display'];

			$iPrice=$data['alias'];
			$this->view->SELECTED ='';
			if(isset ($arrGet['price']) && $iPrice==$arrGet['price']){
				$this->view->SELECTED='selected="selected"';

			}

			$this->view->VALUE =$data['alias'];
			$sPrice.=$this->view->render('common-item/item_price.phtml');
		}
		$this->view->sHTML_PRICE=$sPrice;

		$arStyle= array();
		foreach($arrStyle as $data){
			$this->view->SELECTED='';
			$this->view->NAME =$data['name'];
			$this->view->VALUE =$data['alias'];
			if(isset ($arrGet['style']) && $data['alias']==$arrGet['style'])
			$this->view->SELECTED='selected="selected"';
			$sStyle.=$this->view->render('common-item/item_city.phtml');
			$arStyle[$data['alias']] = $data;
		}
		$this->view->ALIAS_STYLE = $arStyle;
		$this->view->HTML_STYLE = $sStyle;

		$search = $this->view->render('main/search.phtml');
		$this->view->placeholder('search')->set($search);
	}
	public function placeFooter(){

		$ssCity='';

		$link = $this->view->translate('by_city_'.$this->type);

		$arCity =array ();

		foreach($this->view->ARR_CITY as $data){
			$link1 = str_replace ("([a-zA-Z0-9-_]+)",$data['alias'], $link );
			$ssCity.='<li><a href="/'.$link1.'">'.$data['name'].'</a></li>';
			$arCity[$data['alias']] = $data;

			/*if (isset ($this->auth->city_id) && $this->auth->city_id == $data['id']){
			 $this->auth->city_name = $data['name'];
			 }*/
		}
		$this->view->ALIAS_CITY = $arCity;
		$this->view->HTML_CITY=$ssCity;


		//$arManufacture=$this->view->ARR_FACTORY;
		$link = $this->view->translate('by_brand_'.$this->type);
		$ssManufacture='';
		foreach ($this->view->ARR_FACTORY as $data){
			$link1 = str_replace ("([a-zA-Z0-9-_]+)",$data['alias'], $link );
			$ssManufacture.='<li><a href="/'.$link1.'">'.$data['name'].'</a></li>';
			$arManufacture[$data['alias']] = $data;
		}

		// edit by Tin 09/09/2011
		//var_dump($this->view->ARR_FACTORY);
		//$sCategoryAlias = $current['cat_alias']; //$mProduct->getAliasCategoryByID($key);
		//$link_diffirent = str_replace ("([a-zA-Z0-9-_]+)", $sCategoryAlias . '-khac', $link );
		//$ssManufacture .= '<li><a href="/'. $link_diffirent .'"> KhĂ¡c </a></li>';
		//$this->view->sub_content = $html2;
		// End edit by Tin 09/09/2011

		$this->view->ALIAS_MANUFACTURE = $arManufacture;
		$this->view->HTML_MANUFACTURE = $ssManufacture;

		//$arPrice=$this->view->ARR_PRICE;
		$ssPrice='';
		$arPrices =array();
		$link = $this->view->translate('by_price_'.$this->type);
		foreach ($this->view->ARR_PRICE as $data){
			list ($from, $to) = explode('-', $data['alias']);
			$link1 = Common::urlParser(array ($from, $to), $link). '.html';
			$ssPrice.='<li><a href="/'.$link1.'">'.$data['display'].'</a></li>';
			$arPrices[$data['alias']] = $data;
		}

		$this->view->ALIAS_PRICE=$arPrices;
		$this->view->HTML_PRICE=$ssPrice;

		$footer=$this->view->render('main/footer_content.phtml');
		$this->view->placeholder('footer_content')->set($footer);
	}

	public function postDispatch()
	{

		$this->view->PAGE_TITLE=$this->page_title;
		$this->view->DESCRIPTION=$this->page_des;
		$this->view->LOAD_HEADER=$this->load_header;


		//Profile DB
		$db = Zend_Registry::get('db');
		$profiler = $db->getProfiler();
		if($profiler->getEnabled() == false) return;
		$totalTime    = $profiler->getTotalElapsedSecs();
		$queryCount   = $profiler->getTotalNumQueries();
		$longestTime  = 0;
		$longestQuery = null;

		$queries = "";

		$queryString = '<div align="left">';
		$queryString.= 'Executed ' . $queryCount . ' queries in ' . $totalTime . ' seconds' . "<BR>";
		if ($queryCount){
			foreach ($profiler->getQueryProfiles() as $key => $query) {
				if ($query->getElapsedSecs() > $longestTime) {
					$longestTime  = $query->getElapsedSecs();
					$longestQuery = $query->getQuery();
				}
				$queries.= " - $key : " . $query->getQuery() . "<BR>";
			}
			$queryString.= 'Average query length: ' . $totalTime / $queryCount .   ' seconds' . "<BR>";
			$queryString.= 'Queries per second: ' . $queryCount / $totalTime . "<BR>";
			$queryString.= 'Longest query length: ' . $longestTime . "<BR>";
			$queryString.= "Longest query: \n" . $longestQuery . "<BR>";
			$queryString.= "____________________________________________________________________________<BR>";
			$queryString.= $queries;
		}
		$queryString.= '</div>';
		$this->view->queryString = $queryString;
	}
}